#include "LinkedList.h"

template <typename T, typename CLock = CFakeLock>
class CClntList : public CLinkedList<T, CLock>
{
    typedef typename CLinkedList<T, CLock>::Node BaseNode;

public:
    struct ListNode : public CLinkedList<T, CLock>::Node
    {
        friend class CClntList;

    private:
        void *operator new(size_t, void *ptr) _GLIBCXX_USE_NOEXCEPT { return ptr; }
        void operator delete(void *ptr) { memset(ptr, 0, sizeof(ListNode)); } // 只调析构，不释放内存
    };

public:
    BaseNode *NewNode()
    {
        void *ptr = nullptr;

        if (m_lstFree.IsEmpty())
            ptr = malloc(sizeof(ListNode));
        else
            ptr = m_lstFree.PopFront();

        return new (ptr) ListNode();
    }

    BaseNode *NewNode(int iExtLen)
    {
        return nullptr;
    }

    BaseNode *NewNode(void *ptr)
    {
        if (nullptr == ptr)
            return nullptr;

        return new (ptr) ListNode();
    }

    void DeleteNode(BaseNode *pNode)
    {
        // 自动调用Node及其父结构的析构函数,父结构需虚析构函数
        delete (ListNode *)pNode;
        m_lstFree.PushBack(pNode);
    }

    void Destroy()
    {
        ListNode *pNode = nullptr;

        // 本列表中的节点全部析构并放到m_lstFree中
        CLinkedList<T, CLock>::Destroy();
        pNode = (ListNode *)m_lstFree.GetHeader();

        while (nullptr != pNode)
        {
            m_lstFree.Remove(pNode);
            free(pNode);
            pNode = (ListNode *)m_lstFree.GetHeader();
        }
    }

private:
    CLinkedList<T, CLock> m_lstFree;
};
